<!--  -->
<template>
  <div class="redact">
    <div class="img">
      <!-- 小程序公告图标 -->
      <div class="icon_img">
        <span class="text">课程封面图：</span>
        <el-upload
          class="avatar-uploader"
          action="https://api.xujiangyu.com/admin/upimage/"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload_one"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
      <!-- 个人中心背景图 -->
      <div class="icon_img">
        <span class="text">课程分享图：</span>
        <el-upload
          class="avatar-uploader"
          action="https://api.xujiangyu.com/admin/upimage/"
          :show-file-list="false"
          :on-success="handleAvatarSuccess_one"
          :before-upload="beforeAvatarUpload_two"
        >
          <img v-if="imageUrl_one" :src="imageUrl_one" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
      <div class="adduser">
        <!-- 添加公告内容 -->
        <div class="content">
          <span class="text">课程名称：</span>
          <el-input type="textarea" autosize placeholder="请输入内容" v-model="textarea1" @blur="textarea1 = publick.clearinput(textarea1)"></el-input>
        </div>
        <div class="content">
          <span class="text">分类课程名：</span>
          <el-cascader v-model="values" :options="options" @change="handleChange"></el-cascader>
        </div>
        <div class="content">
          <span class="text">课程简介：</span>
          <el-input type="textarea" autosize placeholder="请输入内容" v-model="remake" @blur="remake = publick.clearinput(remake)"></el-input>
        </div>
        <!-- 显示状态 -->
        <div class="content">
          <span class="text">是否展示：</span>
          <el-switch
            style="display: block"
            v-model="is_show"
            active-color="#13ce66"
            active-value="1"
            inactive-value="0"
            active-text="已启用"
            inactive-text="已禁用"
          ></el-switch>
        </div>
        <div class="content">
          <span class="text">是否置顶：</span>
          <el-switch
            style="display: block"
            v-model="is_top"
            active-color="#13ce66"
            active-value="1"
            inactive-value="0"
            active-text="已置顶"
            inactive-text="不置顶"
          ></el-switch>
        </div>
        <div class="content">
          <span class="text">是否免费：</span>
          <el-switch
            style="display: block"
            v-model="is_free"
            active-color="#13ce66"
            active-value="2"
            inactive-value="1"
            active-text="收费"
            inactive-text="免费"
          ></el-switch>
        </div>

        <!-- 添加公告内容 -->

        <!-- <div class="content">
          <span class="text">排序：</span>
          <el-input type="Number" placeholder="请输入排序次数" v-model="sort"></el-input>
        </div> -->
        <!-- 备注 -->
        <div class="content" v-if="is_free == '2'">
          <span class="text">课程价格：</span>
          <el-input type="Number" placeholder="请输入价格" v-model="money"></el-input>
        </div>
        <div class="content">
          <span class="text">视频地址：</span>
          <el-input type="textarea" placeholder="请输入视频链接" v-model="video" @blur="video = publick.clearinput(video)"></el-input>
        </div>
        <div class="content">
          <span class="text">课程总课时:</span>
          <el-input type="Number" placeholder="请输入课时" v-model="class_hour"></el-input>
        </div>
        <div class="content">
          <span class="text">报名人数：</span>
          <el-input type="Number" placeholder="请输入报名人数" v-model="add_num" min="1"></el-input>
        </div>
        <div class="content">
          <span class="text">绑定用户名：</span>
          <el-button type="primary" round @click="()=>this.is_user = true">选择用户</el-button>
        </div>
      </div>
      <div class="userlist" v-if="is_user">
        <table-list :tableData="tableData" :listHeader="listHeader" @operate="operate" :type="type"></table-list>
      </div>
      <div class="userdata" v-if="!is_user && datas.nickName != ''">
        <img :src="datas.avatar" alt class="user_img" />
        <span class="user_name">{{datas.nickName}}</span>
      </div>
      <div class="title">
        <span class="texeS">课程的概述：</span>
        <vue-ueditor-wrap v-model="content" :config="myConfig"></vue-ueditor-wrap>
      </div>
      <button class="but" @click="submit()">确认添加</button>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import VueUeditorWrap from "vue-ueditor-wrap";
import TableList from "../../../components/List/TableList";
export default {
  data() {
    return {
      // 本地路径图片
      imageUrl: "", //公告图标
      imageUrl_one: "", //个人中心背景图
      datas: {},
      options: [],
      values: [],
      placeholders: "请输入内容", //select框中的placehould
      // 以下是返回后台的图片网络路径
      img_gg: "", //公告图标
      cover_img_id: "",
      img_myself: "", //个人中心图
      share_img_id: "",
      type: "addcourse", //列表标识
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      token: {
        token: this.publick.token()
      },
      textarea1: "", //课程名称
      is_show: "",
      is_top: "",
      tableData: [], //列表数据
      listHeader: [], //列表的渲染部分
      is_free: "",
      money: "",
      class_hour: "",
      add_num: "",
      user_id: "",
      course_cate_id: [],
      video: "",
      sort: "",
      remake: "",
      content: "",
      is_user: false, //是否选择用户列表
      api: "https://api.xujiangyu.com/admin", //上传图片域名
      myConfig: {
        // 编辑器不自动被内容撑高
        autoHeightEnabled: true,
        // 初始容器高度
        initialFrameHeight: "500",
        // 初始容器宽度
        initialFrameWidth: "95%",
        // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
        serverUrl: "http://35.201.165.105:8000/controller.php",
        // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
        UEDITOR_HOME_URL: "/UEditor/"
      }
    };
  },
  components: { VueUeditorWrap, TableList },
  //生命周期 - 创建完成（访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    // 直播用户列表
    this.$api
      .anchorList({
        token: this.publick.token()
      })
      .then(res => {
        console.log(res);
        this.tableData = res.data;
      })
      .catch(res => {
        console.log(res);
      });
    this.getCoursecateList();
    let header_name = ["图像", "昵称"]; //列表头部
    let list_content = ["avatar", "nickName"]; //列表渲染内容字段
    for (let key in this.tableData[0]) {
      list_content.push(key);
    }
    for (let i = 0; i < header_name.length; i++) {
      let obj = {
        label: header_name[i],
        prop: list_content[i]
      };
      this.listHeader.push(obj);
    }
    console.log(this.listHeader);
  },
  methods: {
    //   二级分类名
    handleChange(value) {
      console.log(value);
      this.course_cate_id = value;
    },
    //获取二级课程分类
    getCoursecateList() {
      this.$api
        .getCoursecateList({
          pid: 0,
          token: this.publick.token()
        })
        .then(res => {
          console.log(res);
          let datas = res.data;
          let arr = [];
          datas.forEach(e => {
            let obj = {};
            obj.value = e.course_cate_id + "";
            obj.label = e.catename;
            arr.push(obj);
          });
          arr.forEach(e => {
            this.$api
              .getCoursecateList({
                pid: e.value,
                token: this.publick.token()
              })
              .then(res => {
                console.log(res);
                if (res.code == 20000) {
                  e.children = undefined;
                } else {
                  let datas2 = res.data;
                  let arr2 = [];
                  datas2.forEach(e => {
                    let obj = {};
                    obj.value = e.course_cate_id + "";
                    obj.label = e.catename;
                    arr2.push(obj);
                  });
                  console.log(arr2);
                  e.children = arr2;
                }
                this.options.push(e);
              })
              .catch(res => {
                console.log(res);
              });
          });
        })
        .catch(res => {
          console.log(res);
        });
    },
    //   四张图片上传成功是函数
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    handleAvatarSuccess_one(res, file) {
      this.imageUrl_one = URL.createObjectURL(file.raw);
    },
    // 四张图片上传之前的函数
    beforeAvatarUpload_one(file) {
      const isJPG = file.type === "image/jpeg";
      const isGIF = file.type === "image/gif";
      const isPNG = file.type === "image/png";
      const isBMP = file.type === "image/bmp";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.common.errorTip("上传图片必须是JPG/GIF/PNG/BMP 格式!");
      }
      if (!isLt2M) {
        this.common.errorTip("上传图片大小不能超过 2MB!");
      }
      // 上传图片
      var param = new FormData();
      param.append("images", file, file.name);
      param.append("token", this.publick.token());
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      axios.post(this.api + "/upimage", param, config).then(response => {
        console.log(response);
        this.img_gg = response.data.data.images;
        this.cover_img_id = response.data.data.images_id;
      });
      return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
    },
    beforeAvatarUpload_two(file) {
      const isJPG = file.type === "image/jpeg";
      const isGIF = file.type === "image/gif";
      const isPNG = file.type === "image/png";
      const isBMP = file.type === "image/bmp";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.common.errorTip("上传图片必须是JPG/GIF/PNG/BMP 格式!");
      }
      if (!isLt2M) {
        this.common.errorTip("上传图片大小不能超过 2MB!");
      }
      // 上传图片
      var param = new FormData();
      param.append("images", file, file.name);
      param.append("token", this.publick.token());
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      axios.post(this.api + "/upimage", param, config).then(response => {
        this.img_myself = response.data.data.images;
        this.share_img_id = response.data.data.images_id;
      });
      return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
    },
    // 点击提交按钮事件
    submit() {
      console.log(this.value);
      let cate_id = 0;
      if (this.course_cate_id.length > 1) {
        cate_id = this.course_cate_id[1];
      } else {
        cate_id = this.course_cate_id[0];
      }
      this.$api
        .courseAdd({
          course_cate_id: cate_id,
          token: this.publick.token(),
          course_cover_img: this.img_gg,
          cover_img_id: this.cover_img_id,
          course_share_img: this.img_myself,
          share_img_id: this.share_img_id,
          course_name: this.textarea1,
          remake: this.remake,
          content: this.content,
          video: this.video,
          is_show: this.is_show,
          is_top: this.is_top,
          is_free: this.is_free,
          money: this.money,
          class_hour: this.class_hour,
          add_num: this.add_num,
          user_id: this.datas.user_id
        })
        .then(res => {
          this.$message({
            type: "success",
            message: res.message
          });
          this.$router.push({
            path: "/course_list",
            query: {
              type: "addlist"
            }
          });
           this.course_cate_id = [];
         this.img_gg = '',
          this.cover_img_id = '',
          this.img_myself = '',
           this.share_img_id = '',
          this.textarea1 = '',
         this.remake = '',
          this.content = '',
         this.video = '',
          this.is_show = '',
           this.is_top = '',
          this.is_free = '',
           this.money = '',
         this.class_hour = '',
           this.add_num = '',
           this.datas.user_id = '',
           this.imageUrl = '',
           this.imageUrl_one = '',
           this.values = '',
           this.datas = {};
        })
        .catch(res => {
          console.log(res);
        });
    },
    //获取列表操作的数据
    operate(e) {
      this.datas = e;
      if (this.datas.type == "amend") {
        this.is_user = false;
      }
    }
  }
};
</script>
<style scoped>
/* @import url(); 引入css类 */
.redact {
  background: #fff;
  width: 80%;
  margin: auto;
  height: 89vh;
  overflow: auto;
}
/* 上传图片样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.icon_img {
  display: flex;
  width: 50%;
  margin: auto;
  margin-top: 1vh;
  justify-content: flex-start;
  align-items: center;
}
.img {
  width: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 3vh;
}
.flooter {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: 10vh;
}
.color {
  width: 20%;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.but {
  display: flex;
  width: 30%;
  height: 5vh;
  background: #25d22d;
  color: #fff;
  font-size: 16px;
  justify-content: center;
  align-items: center;
  margin: auto;
  margin-top: 10vh;
  outline: none;
}
.title {
  display: flex;
  flex-direction: column;
}
.texeS {
  height: 10vh;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 100%;
}
.adduser {
  width: 100%;
  /* height: 82.1vh; */
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}
.content {
  width: 95%;
  height: 10vh;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.text {
  font-size: 16px;
  min-width: 10%;
}
.userlist {
  width: 98%;
  margin: auto;
  margin-top: 4vh;
}
.userdata {
  width: 98%;
  min-height: 5vh;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.user_img {
  display: block;
  width: 10%;
}
.user_name {
  display: block;
  font-size: 16px;
  margin-left: 3%;
}
</style>